<?php
namespace app\user\controller\staff;

use app\common\controller\UserBase;
use think\facade\View;
use think\facade\Request;
use think\facade\Db;
use think\facade\Config;
use think\facade\Session;
 
use app\user\model\UserGroup;
use app\user\model\UserAuthRule;
use app\user\model\User as UserModel;

class User extends UserBase
{
    public function index()
    {
        return $this->fetch('index');
    }
    public function index_json($limit='',$group_id='')
    {
        $user = new UserModel();
        if($group_id){
            $user = $user->where('group_id',$group_id);
        }
        $list = $user->with(['userGroup'])->order('sort_order desc,id desc')->paginate($limit);
        $this->result($list);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['shop_id'] = ShopId();
            $result = UserModel::create($param);
            if ($result == true) {
                insert_user_log('添加了员工');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }    
        $user_auth = Config::load('user/auth','user_auth');
        return View::fetch('save', ['userAuthGroup' => UserGroup::list_to_level(),'auth'=>$user_auth]);
    }

    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'UserGroup');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //更新数据
            $resule = UserModel::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                insert_user_log('修改了员工信息');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = UserModel::where('id', $id)->find();
        $user_auth = Config::load('user/auth','user_auth');
        return $this->fetch('save', ['data' => $data,'userAuthGroup' => UserGroup::list_to_level(),'auth'=>$user_auth]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            UserModel::destroy($param['id']);
            insert_user_log('删除了用户组');
            $this->success('删除成功');
        }
    }
}
